#include "EntryFontParser.h"

#include "FontDefParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

EntryFontParser::EntryFontParser(
    QStringParser *&_idParser
    , FontDefParser *&_fontDefParser
):    m_idParser(_idParser)
    , m_fontDefParser(_fontDefParser)
{

}

bool EntryFontParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new EntryFont());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("id")))
    {
        data = reader->attributes().value(QStringLiteral("id"));
        if (!m_idParser->parse(reader, data))
            return false;
        m_result->id = m_idParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("id: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (m_fontDefParser->isSubstitution(name))
        {
            if (!m_fontDefParser->parse(reader))
                return false;
            auto result = m_fontDefParser->result();
            m_result->fontDef = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

EntryFont *EntryFontParser::result()
{
    return m_result.take();
}

}